﻿using System;
using System.Collections.ObjectModel;
using System.Net;
using System.Text;
using System.Windows;
using eLearning.Model;
using eLearning.Util;
using Microsoft.Phone.Controls;
using Newtonsoft.Json;

namespace eLearning.View
{
    public partial class RegistrationPage : PhoneApplicationPage
    {
        private bool firstStep = false;
        public ObservableCollection<Angkatan> angkatan;
        
        public RegistrationPage()
        {
            InitializeComponent();
            ListAngkatan();
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            firstStep = false;
        }

        private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            base.OnBackKeyPress(e);

            if (PivotRegistration.SelectedIndex == 1)
            {
                PivotRegistration.SelectedIndex = 0;
            }
            else
            {
                Utility.GotoPage(this, "/View/LoginPage.xaml");
            }
        }

        private void buttonNext_Click(object sender, RoutedEventArgs e)
        {
            if (textBoxNama.Text.Length < 1)
            {
                MessageBox.Show("Nama can't empty");
                textBoxNama.Focus();
                return;
            }
            if (textBoxAlamat.Text.Length < 3)
            {
                MessageBox.Show("Alamat can't empty");
                textBoxAlamat.Focus();
                return;
            }
            if (textBoxEmail.Text.IndexOf("@") < 1)
            {
                MessageBox.Show("Please enter valid Email");
                textBoxEmail.Focus();
                return;
            }
            
            PivotRegistration.SelectedIndex = 1;
            firstStep = true;
        }

        private void hyperlinkLogin_Click(object sender, RoutedEventArgs e)
        {
            Utility.GotoPage(this, "/View/LoginPage.xaml");
        }

        private void buttonRegister_Click(object sender, RoutedEventArgs e)
        {
            if (!firstStep)
            {
                MessageBox.Show("Please complete Your Data first");
                PivotRegistration.SelectedIndex = 0;
                return;
            }
            if (textBoxNim.Text.Length < 1 || !Utility.isNumber(textBoxNim.Text))
            {
                MessageBox.Show("NIM can't empty & must be number");
                textBoxNim.Focus();
                return;
            } 
            if (textBoxUsername.Text.Length < 3)
            {
                MessageBox.Show("Username min 3 char");
                textBoxUsername.Focus();
                return;
            } 
            if (passwordBox.Password.Length < 8)
            {
                MessageBox.Show("Password length at least 8 char");
                passwordBox.Focus();
                return;
            }

            if (!passwordBox.Password.Equals(passwordBoxRe.Password))
            {
                MessageBox.Show("Password not match");
                passwordBoxRe.Focus();
                return;
            }

            //call proses registrasi
            RegistrasiMahasiswa();
            progressBar.Visibility = Visibility.Visible;
        }

        private void RegistrasiMahasiswa()
        {
            //membuat objek mahasiswa yg akan registrasi            
            Mahasiswa mahasiswa = new Mahasiswa();
            mahasiswa.Nama = textBoxNama.Text;
            mahasiswa.Alamat = textBoxAlamat.Text;
            mahasiswa.Telepon = textBoxTelepon.Text;
            mahasiswa.Email = textBoxEmail.Text;
            mahasiswa.Nim = textBoxNim.Text;
            mahasiswa.Username = textBoxUsername.Text;
            mahasiswa.Password = passwordBox.Password;
            mahasiswa.TahunAngkatan = (Angkatan)listAngkatan.SelectedItem;

            //serialisasi objek ke Json
            string json = JsonConvert.SerializeObject(mahasiswa);

            Uri uri = new Uri(Config.Instance.MHS_SERVICE_URL() + Config.REG_ACTION_KEY, UriKind.Absolute);
            WebClient client = new WebClient();

            //Set header
            client.Encoding = Encoding.UTF8;
            client.Headers[HttpRequestHeader.ContentType] = "application/json";
            client.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

            //menangani respon yang diberikan oleh server ketika menjalankan method UploadStringAsync()
            client.UploadStringCompleted += new UploadStringCompletedEventHandler(register_UploadStringCompleted);

            try
            {
                //melakukan UploadString dengan method POST secara asynchronous
                client.UploadStringAsync(uri, "POST", json);
            }
            catch (Exception) { }
        }

        private void register_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                MessageBox.Show("Message : " + e.Result);
                if (e.Result.Contains("Success"))
                {
                    SavedUser.Instance.DestroyUser();
                    Utility.GotoPage(this, "/View/LoginPage.xaml");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR : " + ex.Message);
            }
            progressBar.Visibility = Visibility.Collapsed;
        }

        private void ListAngkatan()
        {
            WebClient webClient = new WebClient();

            string url = Config.Instance.MHS_SERVICE_URL() + Config.ANGKATAN_ACTION_KEY;
            Uri uri = new Uri(url, UriKind.Absolute);
            webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(listAngkatan_DownloadStringCompleted);
            webClient.AllowReadStreamBuffering = true;
            webClient.DownloadStringAsync(uri);
        }

        private void listAngkatan_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {           
            try
            {
                angkatan = JsonConvert.DeserializeObject<ObservableCollection<Angkatan>>(e.Result);
                listAngkatan.ItemsSource = angkatan;        
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

    }
}